package com.wg.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wg.api.client.OrderClient;
import com.wg.api.dto.OrderDTO;
import com.wg.common.constant.JwtClaimsConstant;
import com.wg.common.constant.PageConstant;
import com.wg.common.exception.AccountNotFoundException;
import com.wg.common.exception.FieldNotEmptyException;
import com.wg.common.exception.FieldWrongException;
import com.wg.common.exception.UserExistsException;
import com.wg.common.result.PageResult;
import com.wg.user.enumeration.UserSex;
import com.wg.user.mapper.UserMapper;
import com.wg.user.pojo.dto.UserDTO;
import com.wg.user.pojo.dto.UserLoginDTO;
import com.wg.user.pojo.entity.User;
import com.wg.user.pojo.vo.UserLoginVO;
import com.wg.user.pojo.vo.UserVO;
import com.wg.user.properties.JwtProperties;
import com.wg.user.service.IUserService;
import com.wg.common.util.JwtUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zf_serveer
 * @CreateTime 2025/1/11 0011
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private OrderClient orderClient;

    @Override
    public PageResult pageUsers(Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageNo < 0)
            pageNo = PageConstant.DEFAULT_PAGE_NUM;
        if (pageSize == null || pageSize < 0)
            pageSize = PageConstant.DEFAULT_PAGE_SIZE;
        Page<User> page = new Page<>(pageNo, pageSize);
        page.addOrder(new OrderItem("create_time", false));
        Page<User> pageRes = lambdaQuery().page(page);
        return new PageResult(pageRes.getTotal(), BeanUtil.copyToList(pageRes.getRecords(), UserVO.class));
    }

    @Override
    public PageResult queryAllUsers() {
        List<User> list = lambdaQuery().list();
        return new PageResult(list.size(), BeanUtil.copyToList(list, UserVO.class));
    }

    @Override
    public UserVO getUserById(Long userId) {
        return BeanUtil.copyProperties(this.getById(userId), UserVO.class);
    }

    @Override
    public boolean updateUser(UserDTO userDTO) {
        User user = BeanUtil.copyProperties(userDTO, User.class);
        return this.update(user, new LambdaUpdateWrapper<>(User.class).eq(User::getId, user.getId()));
    }

    @Override
    public boolean deleteUser(Long id) {
        return this.remove(new LambdaUpdateWrapper<>(User.class).eq(User::getId, id));
    }

    @Override
    public boolean addUser(UserDTO userDTO) {
        User user = BeanUtil.copyProperties(userDTO, User.class);
        List<User> list = lambdaQuery().eq(User::getUsername, user.getUsername()).list();
        if (!list.isEmpty()){
            throw new UserExistsException("用户已存在");
        }
        if(user.getSex() == null){
            throw new FieldNotEmptyException("性别不能为空");
        }
        if (!UserSex.MAN.equals(user.getSex()) && !UserSex.WOMAN.equals(user.getSex())){
            throw new FieldWrongException("性别有误");
        }
        user.setCreateTime(LocalDateTime.now());
        return this.save(user);
    }

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        User user = BeanUtil.copyProperties(userLoginDTO, User.class);
        if(user.getUsername() == null || user.getUsername().isBlank()){
            throw new FieldNotEmptyException("用户名不能为空");
        }
        if(user.getPassword() == null || user.getPassword().isBlank()){
            throw new FieldNotEmptyException("密码不能为空");
        }
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getUsername, user.getUsername());
        wrapper.eq(User::getPassword, user.getPassword());
        user = userMapper.selectOne(wrapper);
        if(user == null){
            throw new AccountNotFoundException("用户名或密码有误");
        }
        // 生成Token
        Map<String, Object> claim = new HashMap<>();
        claim.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claim);
        // 创建UserLoginVO对象
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .build();
        return userLoginVO;


    }

    @GlobalTransactional
    @Override
    public boolean addUserAndOrder(UserDTO userDTO, OrderDTO orderDTO) {
        this.addUser(userDTO);
        orderClient.saveOrder(orderDTO);
        return true;
    }
}
